document.addEventListener('DOMContentLoaded', function() {

    //---------------------- 页面初始化阶段----------------------------

    // ===================== func1 获取token ========================
    // 添加 token 验证和获取的函数
    async function validateAndGetAccessToken() {
        const currentToken = localStorage.getItem('access_token');
        const tokenExpTime = localStorage.getItem('acc_token_exp_time');
        const currentTime = new Date().getTime();

        // 检查是否需要获取新token
        if (!currentToken || !tokenExpTime || currentTime > parseInt(tokenExpTime)) {
            try {
                const response = await fetch('https://open.pingcode.com/v1/auth/token?grant_type=client_credentials&client_id=SAfmBLDYTpTs&client_secret=PfLCsCXAEpMiLZiRVkwRGMvw');
                const data = await response.json();
                
                if (data.access_token) {
                    // 存储token
                    localStorage.setItem('access_token', data.access_token);
                    
                    // 设置10天后过期
                    const expTime = new Date().getTime() + (10 * 24 * 60 * 60 * 1000);
                    localStorage.setItem('acc_token_exp_time', expTime.toString());
                    
                    return data.access_token;
                }
            } catch (error) {
                console.error('获取access token失败:', error);
            }
        }
        
        return currentToken;
    }
    // 在初始化时调用token验证
    validateAndGetAccessToken().then(token => {
        if (token) {
            console.log('Token验证成功');
            // 继续执行其他初始化逻辑
        } else {
            console.error('Token获取失败');
        }
    });

    // ===================== func2 获取并显示项目列表 ========================
    projectsData = {
        research: [],
        study: [],
        competition: [],
        development:[],
        other: []
    };
    // 添加获取项目列表的函数
    async function fetchProjects() {
        try {
            const token = await validateAndGetAccessToken();
            if (!token) {
                throw new Error('无法获取访问令牌');
            }

            const response = await fetch('https://open.pingcode.com/v1/project/projects', {
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error('获取项目列表失败');
            }

            const data = await response.json();
            console.log('获取到的项目列表:', data);
            return data;
        } catch (error) {
            console.error('获取项目列表出错:', error);
            return null;
        }
    }
    // 初始化页面时获取项目列表
    async function initializeProjects() {
        try {
            const response = await fetchProjects();
            if (response) {
                // 根据description字段分类项目
                response.values.forEach(project => {
                    const category = project.description || 'other'; // 如果没有description，归类到other
                    if (projectsData[category]) {
                        projectsData[category].push(project);
                    }
                });
                
                // 初始化加载研究类项目
                loadProjectsByType('research');
            }
        } catch (error) {
            console.error('初始化项目列表失败:', error);
        }
        console.log(projectsData);
    }
    // 加载并显示项目列表的函数
    function loadProjectsByType(type) {
        const projectSidebar = document.querySelector('.project-sidebar');
        const mainContent = document.querySelector('.project-content');
        projectSidebar.innerHTML = '';
        
        // 使用内置数据
        const data = projectsData[type];
        console.log(data)
        
        // 如果没有项目，显示空状态
        if (!data || data.length === 0) {
            projectSidebar.innerHTML = '<div class="empty-state">暂无项目</div>';
            
            // 清空主内容区，只保留按钮
            mainContent.innerHTML = `
                <div class="empty-content">
                    <div class="action-buttons">
                        <button class="btn add-member">加入项目</button>
                        <button class="btn new-project">新建项目</button>
                    </div>
                </div>
            `;
            return;
        }

        // 有项目时的正常渲染逻辑
        data.forEach((project, index) => {
            const div = document.createElement('div');
            div.className = 'project-item' + (index === 0 ? ' active' : '');
            div.setAttribute('data-project-id', project.id);
            div.setAttribute('data-project-type', project.type);
            div.innerHTML = `
                <span class="project-name">${project.name}</span>
                <span class="project-status ${project.state?.type || 'normal'}">${project.state?.name || '未设置'}</span>
            `;
            
            div.addEventListener('click', function() {
                document.querySelectorAll('.project-item').forEach(item => 
                    item.classList.remove('active'));
                this.classList.add('active');
                loadProjectDetails(project);
            });
            
            projectSidebar.appendChild(div);
        });

        // 默认加载第一个项目的详情
        if (data.length > 0) {
            loadProjectDetails(data[0]);
        }
    }
    // 调用初始化函数
    initializeProjects();


    // ===================== func3 获取并显示工作项详情 ========================
    projectItem = {
    }
    // 添加获取工作项列表的函数
    async function fetchWorkItems(projectId) {
        try {
            const token = await validateAndGetAccessToken();
            if (!token) {
                throw new Error('无法获取访问令牌');
            }

            const response = await fetch(`https://open.pingcode.com/v1/project/work_items?project_ids=${projectId}`, {
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error('获取工作项列表失败');
            }

            const data = await response.json();
            console.log('获取到的工作项列表:', data);
            projectItem = data
            return data;
        } catch (error) {
            console.error('获取工作项列表出错:', error);
            return null;
        }
    }
    // 修改加载项目详情的函数
    async function loadProjectDetails(project) {
        console.log(project)
        const mainContent = document.querySelector('.project-content');
        
        mainContent.innerHTML = `
            <div class="container">
                <div class="project-header">
                    <div class="project-title">
                        <h1>${project.name}</h1>
                        <div class="project-tags">
                            <span class="tag">项目类型: ${project.type === 'scrum' ? '敏捷开发' : 
                                          project.type === 'waterfall' ? '瀑布开发' : project.type}</span>
                        </div>
                    </div>
                    <div class="action-buttons">
                        <button class="btn add-member">加入项目</button>
                        <button class="btn new-project">新建项目</button>
                    </div>
                </div>

                <!-- 添加状态和优先级选择器 -->
                <div class="project-status-section">
                    <div class="status-select">
                        <label>项目状态</label>
                        <select class="status-dropdown">
                            <option value="pending" ${project.state?.type === 'pending' ? 'selected' : ''}>未完成</option>
                            <option value="in_progress" ${project.state?.type === 'in_progress' ? 'selected' : ''}>进行中</option>
                            <option value="done" ${project.state?.type === 'done' ? 'selected' : ''}>已完成</option>
                        </select>
                    </div>
                    <div class="priority-select">
                        <label>项目优先级</label>
                        <select class="priority-dropdown">
                            <option value="5cb9466afda1ce4ca0090005" ${project.priority?.id === '5cb9466afda1ce4ca0090005' ? 'selected' : ''}>最高</option>
                            <option value="5cb9466afda1ce4ca0090004" ${project.priority?.id === '5cb9466afda1ce4ca0090004' ? 'selected' : ''}>较高</option>
                            <option value="5cb9466afda1ce4ca0090003" ${project.priority?.id === '5cb9466afda1ce4ca0090003' ? 'selected' : ''}>普通</option>
                            <option value="5cb9466afda1ce4ca0090002" ${project.priority?.id === '5cb9466afda1ce4ca0090002' ? 'selected' : ''}>较低</option>
                        </select>
                    </div>
                </div>

                <div class="project-info">
                    <p>创建时间: ${new Date(project.created_at * 1000).toLocaleDateString()}</p>
                    <p>最后更新: ${new Date(project.updated_at * 1000).toLocaleDateString()}</p>
                </div>
                <div class="milestone-table">
                    <table>
                        <thead>
                            <tr>
                                <th>序号</th>
                                <th>名称</th>
                                <th>负责人</th>
                                <th>截止日期</th>
                                <th>状态</th>
                                <th>优先级</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>

                <!-- 添加工作记录部分 -->
                <div class="work-notes-section">
                    <div class="current-work">
                        <h3>工作记录：${project.name}</h3>
                        <textarea 
                            class="work-notes" 
                            placeholder="在这里填写今天的工作记录"
                            rows="4"
                        >${project.description || ''}</textarea>
                    </div>
                    <div class="button-group">
                        <button class="btn submit">提交</button>
                        <button class="btn add-milestone">添加里程碑</button>
                    </div>
                </div>
            </div>
        `;

        // 添加提交按钮事件监听
        document.querySelector('.submit').addEventListener('click', function() {
            const notes = document.querySelector('.work-notes').value;
            if (notes.trim()) {
                alert('工作记录已提交！');
                document.querySelector('.work-notes').value = '';
            } else {
                alert('请填写工作记录！');
            }
        });

        // 获取并渲染工作项列表
        try {
            const workItemsData = await fetchWorkItems(project.id);
            if (workItemsData) {
                // 使用现有的渲染函数渲染工作项
                renderMilestones(project.id);
            }
        } catch (error) {
            console.error('加载工作项失败:', error);
        }
    }
    // 处理工作项数据，将其组织为阶段和里程碑的结构
    function processWorkItems(items) {
        // 首先找出所有阶段（没有parent_id的项目）
        const stages = items.filter(item => !item.parent_id);
        
        // 为每个阶段找到其对应的里程碑（子任务）
        return stages.map(stage => ({
            id: stage.id,
            name: stage.title,
            identifier: stage.identifier,
            owner: stage.assignee?.display_name || '未分配',
            deadline: stage.end_at ? new Date(stage.end_at * 1000).toLocaleDateString() : '未设置',
            status: stage.state?.name || '未设置',
            priority: stage.priority?.name || '普通',
            submilestones: items
                .filter(item => item.parent_id === stage.id)
                .map(sub => ({
                    id: sub.id,
                    name: sub.title,
                    identifier: sub.identifier,
                    owner: sub.assignee?.display_name || '未分配',
                    deadline: sub.end_at ? new Date(sub.end_at * 1000).toLocaleDateString() : '未设置',
                    status: sub.state?.name || '未设置',
                    priority: sub.priority?.name || '普通'
                }))
        }));
    }

    // 修改渲染表格的函数
    function renderMilestones(projectId) {
        const tbody = document.querySelector('tbody');
        if (!tbody) return; // 如果表格不存在则返回
        
        tbody.innerHTML = '';
        
        // 如果没有projectId，清空表格并返回
        if (!projectId) return;
        
        // 根据项目ID过滤工作项
        const projectWorkItems = projectItem.values.filter(item => 
            item.project.id === projectId
        );
        console.log("projectWorkItems",projectWorkItems)
        
        // 如果没有工作项，也返回
        if (!projectWorkItems.length) return;
        
        // 处理工作项数据
        const stages = processWorkItems(projectWorkItems);
        
        stages.forEach(stage => {
            // 创建阶段行
            const tr = document.createElement('tr');
            tr.setAttribute('data-milestone-id', stage.id);
            tr.className = 'stage-row';
            tr.innerHTML = `
                <td>${stage.identifier}</td>
                <td>
                    <div class="milestone-name">
                        <span class="expand-icon">${stage.submilestones.length > 0 ? '▶' : ''}</span>
                        ${stage.name}
                    </div>
                </td>
                <td>${stage.owner}</td>
                <td>${stage.deadline}</td>
                <td>
                    <span class="status-badge ${stage.status.replace(/\s+/g, '-').toLowerCase()}">
                        ${stage.status}
                    </span>
                </td>
                <td>
                    <span class="priority-badge ${stage.priority.replace(/\s+/g, '-').toLowerCase()}">
                        ${stage.priority}
                    </span>
                </td>
                <td>
                    <button class="btn edit">编辑</button>
                </td>
            `;
            tbody.appendChild(tr);

            // 如果有子里程碑，添加隐藏的子里程碑行
            if (stage.submilestones.length > 0) {
                stage.submilestones.forEach(sub => {
                    const subTr = document.createElement('tr');
                    subTr.className = `submilestone submilestone-${stage.id}`;
                    subTr.style.display = 'none';
                    subTr.innerHTML = `
                        <td>${sub.identifier}</td>
                        <td style="padding-left: 30px;">${sub.name}</td>
                        <td>${sub.owner}</td>
                        <td>${sub.deadline}</td>
                        <td>
                            <span class="status-badge ${sub.status.replace(/\s+/g, '-').toLowerCase()}">
                                ${sub.status}
                            </span>
                        </td>
                        <td>
                            <span class="priority-badge ${sub.priority.replace(/\s+/g, '-').toLowerCase()}">
                                ${sub.priority}
                            </span>
                        </td>
                        <td>
                            <button class="btn edit">编辑</button>
                        </td>
                    `;
                    tbody.appendChild(subTr);
                });
            }
        });

        // 添加展开/折叠功能
        addExpandListeners();
    }
    




    //----------------------- 页面初始化阶段 ----------------------------


    // 提交工作记录
    document.querySelector('.submit').addEventListener('click', function() {
        const notes = document.querySelector('textarea').value;
        if (notes.trim()) {
            alert('工作记录已提交！');
            document.querySelector('textarea').value = '';
        }
    });

    // 初始化渲染
    renderMilestones();

    // 主导航切换
    const mainNavItems = document.querySelectorAll('.main-sidebar .nav-item');
    mainNavItems.forEach(item => {
        item.addEventListener('click', function() {
            // 移除所有active类
            mainNavItems.forEach(nav => nav.classList.remove('active'));
            // 添加active类到当前点击项
            this.classList.add('active');
            // 加载对应类型的项目列表
            loadProjectsByType(this.dataset.type);
        });
    });

    // 项目列表切换
    const projectItems = document.querySelectorAll('.project-sidebar .project-item');
    projectItems.forEach(item => {
        item.addEventListener('click', function() {
            // 移除所有active类
            projectItems.forEach(proj => proj.classList.remove('active'));
            // 添加active类到当前点击项
            this.classList.add('active');
            // 加载项目详情
            loadProjectDetails(this.textContent);
        });
    });

    // 直接在代码中定义项目数据




   



    

    // 添加新的样式
    const style = document.createElement('style');
    style.textContent = `
        .empty-state {
            padding: 20px;
            text-align: center;
            color: #999;
        }
        
        .empty-content {
            display: flex;
            justify-content: flex-end;
            padding: 20px;
        }
        
        .action-buttons {
            display: flex;
            gap: 10px;
        }
    `;
    document.head.appendChild(style);

    // 初始化加载研究类项目
    loadProjectsByType('research');

    // 添加展开/折叠监听器
    function addExpandListeners() {
        const expandIcons = document.querySelectorAll('.expand-icon');
        expandIcons.forEach(icon => {
            icon.addEventListener('click', function(e) {
                const milestoneRow = e.target.closest('tr');
                const milestoneId = milestoneRow.getAttribute('data-milestone-id');
                const submilestones = document.querySelectorAll(`.submilestone-${milestoneId}`);
                
                // 切换箭头方向
                if (this.textContent === '▶') {
                    this.textContent = '▼';
                    submilestones.forEach(row => row.style.display = 'table-row');
                } else {
                    this.textContent = '▶';
                    submilestones.forEach(row => row.style.display = 'none');
                }
            });
        });
    }

    // 添加弹窗HTML到body
    function createModal() {
        const modalHTML = `
            <div class="modal" id="newProjectModal">
                <div class="modal-content">
                    <div class="modal-header">
                        <h2>新建项目</h2>
                        <span class="close">&times;</span>
                    </div>
                    <div class="modal-body">
                        <form id="newProjectForm">
                            <div class="form-group">
                                <label for="projectName">项目名称</label>
                                <input type="text" id="projectName" required>
                            </div>
                            <div class="form-group">
                                <label for="projectIdentifier">项目标识</label>
                                <input type="text" id="projectIdentifier" required>
                            </div>
                            <div class="form-group">
                                <label for="projectOwner">负责人</label>
                                <input type="text" id="projectOwner" required>
                            </div>
                            <div class="form-group">
                                <label for="startDate">开始时间</label>
                                <input type="date" id="startDate" required>
                            </div>
                            <div class="form-group">
                                <label for="endDate">结束时间</label>
                                <input type="date" id="endDate" required>
                            </div>
                            <div class="form-actions">
                                <button type="button" class="btn cancel">取消</button>
                                <button type="submit" class="btn submit">确定</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        `;
        document.body.insertAdjacentHTML('beforeend', modalHTML);
    }

    // 初始化弹窗事件
    function initializeModal() {
        createModal();
        const modal = document.getElementById('newProjectModal');
        const closeBtn = modal.querySelector('.close');
        const cancelBtn = modal.querySelector('.btn.cancel');
        const form = document.getElementById('newProjectForm');

        // 点击新建项目按钮显示弹窗
        document.querySelectorAll('.new-project').forEach(btn => {
            btn.addEventListener('click', () => {
                modal.style.display = 'block';
            });
        });

        // 关闭弹窗的多种方式
        closeBtn.onclick = () => modal.style.display = 'none';
        cancelBtn.onclick = () => modal.style.display = 'none';
        window.onclick = (event) => {
            if (event.target === modal) {
                modal.style.display = 'none';
            }
        };

        // 表单提交处理
        form.onsubmit = (e) => {
            e.preventDefault();
            const newProject = {
                name: document.getElementById('projectName').value,
                identifier: document.getElementById('projectIdentifier').value,
                owner: document.getElementById('projectOwner').value,
                startDate: document.getElementById('startDate').value,
                endDate: document.getElementById('endDate').value
            };
            
            // 这里可以添加向后端提交数据的逻辑
            console.log('新项目数据：', newProject);
            
            // 关闭弹窗并重置表单
            modal.style.display = 'none';
            form.reset();
        };
    }

    // 初始化弹窗
    initializeModal();

    // 添加里程碑弹窗HTML
    function createMilestoneModal() {
        const modalHTML = `
            <div class="modal" id="newMilestoneModal">
                <div class="modal-content">
                    <div class="modal-header">
                        <h2>添加里程碑</h2>
                        <span class="close">&times;</span>
                    </div>
                    <div class="modal-body">
                        <form id="newMilestoneForm">
                            <div class="form-group">
                                <label for="milestoneTitle">里程碑标题</label>
                                <input type="text" id="milestoneTitle" required>
                            </div>
                            <div class="form-group">
                                <label for="milestoneStartDate">开始时间</label>
                                <input type="date" id="milestoneStartDate" required>
                            </div>
                            <div class="form-group">
                                <label for="milestoneEndDate">结束时间</label>
                                <input type="date" id="milestoneEndDate" required>
                            </div>
                            <div class="form-group">
                                <label for="milestonePriority">优先级</label>
                                <select id="milestonePriority" required>
                                    <option value="highest">最高</option>
                                    <option value="high">较高</option>
                                    <option value="normal" selected>普通</option>
                                    <option value="low">较低</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="milestoneStatus">状态</label>
                                <select id="milestoneStatus" required>
                                    <option value="not_started">未开始</option>
                                    <option value="in_progress">进行中</option>
                                    <option value="completed">已完成</option>
                                    <option value="pending">待处理</option>
                                </select>
                            </div>
                            <div class="form-actions">
                                <button type="button" class="btn cancel">取消</button>
                                <button type="submit" class="btn submit">确定</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        `;
        document.body.insertAdjacentHTML('beforeend', modalHTML);
    }

    // 初始化里程碑弹窗事件
    function initializeMilestoneModal() {
        createMilestoneModal();
        const modal = document.getElementById('newMilestoneModal');
        const closeBtn = modal.querySelector('.close');
        const cancelBtn = modal.querySelector('.btn.cancel');
        const form = document.getElementById('newMilestoneForm');

        // 点击添加里程碑按钮显示弹窗
        document.querySelectorAll('.add-milestone').forEach(btn => {
            btn.addEventListener('click', () => {
                modal.style.display = 'block';
                
                // 设置默认日期为今天
                const today = new Date().toISOString().split('T')[0];
                document.getElementById('milestoneStartDate').value = today;
                document.getElementById('milestoneEndDate').value = today;
            });
        });

        // 关闭弹窗的多种方式
        closeBtn.onclick = () => modal.style.display = 'none';
        cancelBtn.onclick = () => modal.style.display = 'none';
        window.onclick = (event) => {
            if (event.target === modal) {
                modal.style.display = 'none';
            }
        };

        // 表单提交处理
        form.onsubmit = (e) => {
            e.preventDefault();
            
            // 验证结束时间不早于开始时间
            const startDate = new Date(document.getElementById('milestoneStartDate').value);
            const endDate = new Date(document.getElementById('milestoneEndDate').value);
            
            if (endDate < startDate) {
                alert('结束时间不能早于开始时间！');
                return;
            }

            const newMilestone = {
                title: document.getElementById('milestoneTitle').value,
                startDate: document.getElementById('milestoneStartDate').value,
                endDate: document.getElementById('milestoneEndDate').value,
                priority: document.getElementById('milestonePriority').value,
                status: document.getElementById('milestoneStatus').value
            };
            
            // 这里可以添加向后端提交数据的逻辑
            console.log('新里程碑数据：', newMilestone);
            
            // 关闭弹窗并重置表单
            modal.style.display = 'none';
            form.reset();
        };
    }

    // 初始化里程碑弹窗
    initializeMilestoneModal();

    
}); 